#include <iostream>
#include <thread>
#include <vector>
#include "threadsafe_queue.cpp"  // 包含 threadsafe_queue 的定义

// 测试函数：单线程操作队列
void single_thread_test() {
    threadsafe_queue<int> queue;
    std::cout << "[单线程测试] 开始..." << std::endl;

    // 插入数据
    queue.push(10);
    queue.push(20);
    queue.push(30);

    // 弹出数据并验证
    int value;
    queue.wait_and_pop(value);
    std::cout << "弹出数据: " << value << " (期望: 10)" << std::endl;

    queue.wait_and_pop(value);
    std::cout << "弹出数据: " << value << " (期望: 20)" << std::endl;

    queue.wait_and_pop(value);
    std::cout << "弹出数据: " << value << " (期望: 30)" << std::endl;

    std::cout << "[单线程测试] 完成" << std::endl;
}

// 测试函数：多线程生产和消费
void multi_thread_test() {
    threadsafe_queue<int> queue;
    std::cout << "[多线程测试] 开始..." << std::endl;

    const int num_threads = 4;
    const int num_elements = 10;

    // 生产者线程
    auto producer = [&queue, num_elements](int id) {
        for (int i = 0; i < num_elements; ++i) {
            int value = id * 100 + i;
            queue.push(value);
            std::cout << "生产者 " << id << " 插入数据: " << value << std::endl;
        }
    };

    // 消费者线程
    auto consumer = [&queue, num_elements]() {
        for (int i = 0; i < num_elements; ++i) {
            int value;
            queue.wait_and_pop(value);
            std::cout << "消费者弹出数据: " << value << std::endl;
        }
    };

    // 启动线程
    std::vector<std::thread> producers;
    std::vector<std::thread> consumers;

    for (int i = 0; i < num_threads; ++i) {
        producers.emplace_back(producer, i);
        consumers.emplace_back(consumer);
    }

    // 等待线程完成
    for (auto& producer : producers) {
        producer.join();
    }
    for (auto& consumer : consumers) {
        consumer.join();
    }

    std::cout << "[多线程测试] 完成" << std::endl;
}

// 测试函数：空队列行为
void empty_queue_test() {
    threadsafe_queue<int> queue;
    std::cout << "[空队列测试] 开始..." << std::endl;

    int value;

    // 尝试弹出数据（非阻塞）
    if (queue.try_pop(value)) {
        std::cout << "弹出数据: " << value << std::endl;
    } else {
        std::cout << "try_pop: 队列为空，未弹出数据" << std::endl;
    }

    // 检查队列是否为空
    if (queue.empty()) {
        std::cout << "队列为空 (期望: 为空)" << std::endl;
    } else {
        std::cout << "队列不为空 (期望: 为空)" << std::endl;
    }

    std::cout << "[空队列测试] 完成" << std::endl;
}

int main() {
    // 单线程测试
    single_thread_test();

    // 多线程测试
    multi_thread_test();

    // 空队列测试
    empty_queue_test();

    return 0;
}
